package ch.jamme.conf.def;

import java.text.*;
import java.util.*;

import ch.jamme.conf.*;
import ch.jamme.exception.*;
import ch.jamme.util.*;

/**
 * Converts an object in its String representation and conversely a String in the Object that it represents (given its Class)
 * @author Mario Fusco
 */
public class DefaultObjectToStringConvertor implements ObjectToStringConvertor {

	public static final DateFormat DEFAULT_DATE_FORMAT = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss.SSS");
	
	/**
	 * Converts an object in its representation as a String
	 * @param object The object to be converted
	 * @return The String representing the object
	 */
	public String toString(Object object) {
		if (object instanceof Date) return getDateFormat().format((Date)object);
		return object.toString();
	}

	/**
	 * Instances an Object starting from its Class and its representation as a String
	 * @param clazz The Class of the object to be instanciated
	 * @param asString The object's String representation
	 * @return The instanciated Object of the given Class and having the given String representation
	 */
	public Object toObject(Class<?> clazz, String asString) {
		if (Date.class.isAssignableFrom(clazz)) {
			try {
				if (asString == null || asString.trim().length() == 0) return null;
				return getDateFormat().parse(asString);
			} catch (ParseException e) {
				throw new JammeException("Unable to parse date " + asString, e);
			}
		}
		return IntrospectionUtil.getObjectByStringConstructor(clazz, asString);
	}
	
	/**
	 * Returns the DateFormat used to convert a date back and forward to its String representation.
	 * Override this method if you only want to change the used date format without affecting the default
	 * object to string conversion algorithm.
	 * @return The DateFormat used to convert a date
	 */
	protected DateFormat getDateFormat() {
		return DEFAULT_DATE_FORMAT;
	}
}
